<template>
  <view>
    <view class="section">
      <view class="title">人员在线汇总</view>

      <view class="flex justify-between person-wrap">
        <view>
          <image class="icon" src="/static/images/locate/p1.png"></image>
          <view class="label">员工(人)</view>
          <view class="value">{{ person[1] }}</view>
        </view>
        <view>
          <image class="icon" src="/static/images/locate/p2.png"></image>
          <view class="label">承包商(人)</view>
          <view class="value">{{ person[2] }}</view>
        </view>
        <view>
          <image class="icon" src="/static/images/locate/p3.png"></image>
          <view class="label">访客(人)</view>
          <view class="value">{{ person[3] }}</view>
        </view>
      </view>
    </view>

    <view class="section">
      <view class="title">车辆在线汇总</view>

      <view class="chart-wrap">
        <qiun-data-charts v-if="chartsDataPie" :opts="opts" type="ring" :chartData="chartsDataPie" />
        <view v-else class="empty-info">暂无车辆数据</view>
      </view>
    </view>

    <view class="section">
      <view class="tabs flex">
        <view
          v-for="item in tabs"
          :key="item.value"
          @click="currTab = item.value"
          class="tabs-item"
          :class="{ active: currTab === item.value }"
        >
          <view class="tab-title">{{ item.name }}</view>
          <view class="border"></view>
        </view>
      </view>

      <view class="tree-wrap">
        <view class="t-head flex justify-between">
          <view class="flex-auto title-td">区域</view>
          <view class="p-td mr-20">人员</view>
          <view class="p-td">车辆</view>
        </view>

        <cu-tree v-if="currTab === 1" value="areaId" label="areaName" child="childList" :data="areaData"></cu-tree>
        <cu-tree v-else value="id" label="label" child="children" :data="deptData"></cu-tree>
      </view>
    </view>
  </view>
</template>

<script>
import { getAreaData, getDeptData, getStatData, getModelList, getVehicleTypeList } from '@/api/locate/stat'
import { guid, flattenTree, childRecursion } from '@/pages/work/person-stat/util'
import cuTree from './cu-tree.vue'

export default {
  name: 'person-stat',

  components: {
    cuTree
  },

  data() {
    return {
      timer: null,
      modelId: null,
      carBizData: {},
      person: {
        1: 0,
        2: 0,
        3: 0
      },
      tabs: [
        {
          name: '区域统计',
          value: 1
        },
        {
          name: '部门统计',
          value: 2
        }
      ],
      currTab: 1,
      chartsDataPie: null,
      areaData: [],
      deptData: [],
      opts: {
        animation: false,
        rotate: false,
        rotateLock: false,
        color: ['#F69E2C', '#8A87FC', '#FAC858', '#EE6666', '#73C0DE', '#3CA272', '#FC8452', '#9A60B4', '#ea7ccc'],
        padding: [5, 50, 5, 5],
        dataLabel: true,
        enableScroll: false,
        legend: {
          show: true,
          position: 'right',
          lineHeight: 25
        },
        title: {
          name: '0',
          fontSize: 16,
          color: '#333333'
        },
        subtitle: {
          name: '总数(辆)',
          fontSize: 10,
          color: '#999999'
        },
        extra: {
          ring: {
            ringWidth: 20,
            activeOpacity: 0.5,
            activeRadius: 0,
            offsetAngle: 0,
            labelWidth: 0,
            border: false
          }
        }
      }
    }
  },

  async onLoad() {
    await getAreaData().then((res) => {
      const list = res.data.length === 1 ? res.data[0].childList : res.data
      this.areaData = list
      this.$store.commit('cockpit/setAreaInfo', flattenTree(this.areaData, 'childList'))
    })
    await getDeptData().then((res) => {
      const list = res.data
      this.deptData = list
    })
    this.fetchStatData()

    this.getModelId()
    this.fetchCarBizType()
    this.timer = setInterval(() => {
      this.fetchStatData()
    }, 10000)
  },

  beforeDestroy() {
    this.timer && clearInterval(this.timer)
    this.$socket.closeSocket()
  },

  methods: {
    // 获取车辆类型名称
    fetchCarBizType() {
      getVehicleTypeList().then((res) => {
        res.rows.forEach((item) => {
          this.carBizData[item.typeId] = item
        })

        // this.setCarNum([])
        // setInterval(() => {
        //   this.setCarNum([
        //     {bizType: 28, cardType: 2},
        //     {bizType: 28, cardType: 2},
        //     {bizType: 28, cardType: 2},
        //     {bizType: 29, cardType: 2},
        //   ])
        // }, 3000)
      })
    },

    fetchStatData() {
      if (!this.modelId) return

      getStatData(this.modelId).then(({ data }) => {
        const areaCountMap = {}
        data.areaStats.forEach((item) => {
          areaCountMap[item.key] = item
        })
        this.areaTreeMap(this.areaData, areaCountMap)

        const deptCountMap = {}
        data.deptStats.forEach((item) => {
          deptCountMap[item.key] = item
        })

        this.deptTreeMap(this.deptData, deptCountMap)
        this.deptData.map((item) => childRecursion(item, deptCountMap))
      })
    },

    areaTreeMap(arr, countObj = {}) {
      for (const node of arr) {
        const count = countObj[node.areaId]
          ? countObj[node.areaId]
          : {
              personnelCount: 0,
              carCount: 0
            }
        this.$set(node, 'count', count)
        this.$set(node, 'open', true)
        if (node.childList) {
          this.areaTreeMap(node.childList, countObj)
        }
      }
    },

    deptTreeMap(arr, countObj = {}) {
      for (const node of arr) {
        const count = countObj[node.id]
          ? countObj[node.id]
          : {
              personnelCount: 0,
              carCount: 0
            }
        this.$set(node, 'count', count)
        this.$set(node, 'open', true)
        if (node.children) {
          this.deptTreeMap(node.children, countObj)
        }
      }
    },

    getModelId() {
      if (this.modelId) return

      getModelList().then((res) => {
        this.modelId = res.rows[0].modelId
        this.fetchStatData()
        this.initSocket()
      })
    },

    initSocket() {
      this.$socket.onSocket({
        userId: this.modelId,
        modelId: this.modelId
      })

      this.$socket.socket.on('locate-platform', (data) => {
        const locateData = JSON.parse(data)
        const personObj = {
          1: 0,
          2: 0,
          3: 0
        }
        locateData.forEach((item) => {
          if (item.cardType === 1) {
            // 人
            personObj[item.bindType] += 1
          }
        })
        this.person = personObj

        this.setCarNum(locateData)

        this.$store.commit(
          'cockpit/setCardInfo',
          locateData.map((item) => ({
            ...item,
            id: `${item.cardType === 1 ? 'person' : 'car'}-${item.bindId || guid(8)}`
          }))
        )
      })
    },

    setCarNum(locateData) {
      if (Object.keys(this.carBizData).length === 0) return

      const cars = locateData.filter((item) => item.cardType === 2)

      const carCountObj = {}
      cars.forEach((item) => {
        carCountObj[item.bizType] = carCountObj[item.bizType] ? carCountObj[item.bizType] + 1 : 1
      })

      const data = []
      Object.keys(carCountObj).forEach((key) => {
        data.push({
          name: this.carBizData[key] ? this.carBizData[key].businessType : '未知',
          value: carCountObj[key]
        })
      })
      console.log('data', data)
      this.chartsDataPie = {
        series: [
          {
            data: data.map((item) => ({
              ...item,
              legendText: `${item.name} ${item.value}`
            }))
          }
        ]
      }
      this.opts.title.name = cars.length
    }
  }
}
</script>

<style lang="scss" scoped>
.section {
  background: #fff;
  margin: 20rpx;
  padding: 24rpx;

  .title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 20rpx;
  }

  .person-wrap {
    padding: 0 40rpx;
    text-align: center;

    .label {
      color: #666666;
      font-size: 12px;
      margin: 16rpx 0;
    }

    .value {
      color: #333333;
      font-size: 16px;
      font-weight: 600;
    }
  }

  .chart-wrap {
    width: 700rpx;
    height: 300rpx;
  }

  .icon {
    width: 110rpx;
    height: 110rpx;
  }

  .tabs-item {
    margin-right: 30rpx;
    position: relative;
    padding-bottom: 10rpx;
    margin-bottom: 10rpx;

    .tab-title {
      font-size: 16px;
      font-weight: bold;
      color: #777777;
    }

    &.active {
      .tab-title {
        color: #333333;
      }

      .border {
        height: 6rpx;
        width: 32rpx;
        background: #3685fb;
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translate(-50%, 0);
      }
    }
  }
}

.tree-wrap {
  .t-head {
    color: #666666;
    font-size: 12px;
    padding: 10px 15px;
  }

  .title-td {
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }

  .p-td {
    width: 80rpx;
    flex-grow: 0;
  }

  .t-row {
    background: #f3f4f8;
    font-size: 15px;
    color: #333333;
    padding: 20rpx;
    margin-bottom: 6rpx;
  }

  .arrow-icon {
    width: 21rpx;
    height: 24rpx;
    margin-right: 10rpx;
  }
}

.empty-info {
  padding-left: 20rpx;
  color: #666666;
}
</style>
